import { useParams as useRemixParams } from '@remix-run/react';
import { useConfig } from './D8dConfigProvider.tsx';
import { useMemo } from 'react';
import { extractParamsFromPath, findMatchingPattern } from '../utils/fun.ts';

/**
 * 用于获取路由参数的hook
 * 
 * 示例：
 * - 路由 "/member/:id"
 * - 访问 "/member/123"
 * - useParams() 返回 { id: '123' }
 */
export const useParams = (): Record<string, string | undefined> => {
  const { useSpaRouter, pages, userMenu } = useConfig();
  const remixParams = useRemixParams();
  
  // 在SPA模式下，自定义实现路由参数解析
  const customParams = useMemo(() => {
    if (!useSpaRouter) {
      return remixParams;
    }
    
    // 获取当前路径
    const currentPath = window.location.pathname;
    const params: Record<string, string> = {};
    
    // 1. 收集所有可能的路由模式
    const possiblePatterns: string[] = [];
    
    // 从页面配置中收集路由模式
    pages.forEach(page => {
      if (page.path && page.path.includes(':')) {
        possiblePatterns.push(page.path);
      }
    });
    
    // 从菜单中收集路由模式
    userMenu?.forEach(item => {
      if (item.page_path && item.page_path.includes(':')) {
        possiblePatterns.push(item.page_path);
      }
    });
    
    // 2. 查找匹配的路由模式并提取参数
    if (possiblePatterns.length > 0) {
      const matchingPattern = findMatchingPattern(possiblePatterns, currentPath);
      if (matchingPattern) {
        const extractedParams = extractParamsFromPath(matchingPattern, currentPath);
        Object.assign(params, extractedParams);
      }
    }
    
    // 3. 同时获取查询字符串参数
    const urlParams = new URLSearchParams(window.location.search);
    urlParams.forEach((value, key) => {
      params[key] = value;
    });
    
    // 4. 回退方案：如果没有从路由模式中提取到参数，检查最后一段是否像ID
    if (Object.keys(params).length === 0 || !params['id']) {
      const pathSegments = currentPath.split('/').filter(Boolean);
      const lastSegment = pathSegments[pathSegments.length - 1];
      
      if (lastSegment && (
        /^\d+$/.test(lastSegment) || 
        /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(lastSegment)
      )) {
        params['id'] = lastSegment;
      }
    }
    
    return params;
  }, [useSpaRouter, remixParams, pages, userMenu]);
  
  return useSpaRouter ? customParams : remixParams;
}; 